<template>
    <my-container v-loading="pageLoading">
      <!--查询-->
      <template #header>
        <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model="filter.name"
              placeholder="服务名"
              clearable
              @keyup.enter.native="onSearch"
            >
              <template #prefix>
                <i class="el-input__icon el-icon-search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" icon="el-icon-search" @click="onSearch">查询</el-button>
          </el-form-item>
          <el-form-item v-if="checkPermission(['admin_sysrole_add'])">
            <el-button type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
          </el-form-item>
          <el-form-item v-if="checkPermission(['admin_sysrole_delete'])">
            <my-confirm-button
              :disabled="sels.length === 0"
              :type="'delete'"
              :placement="'bottom-end'"
              :loading="deleteLoading"
              style="margin-left: 0px;"
              @click="onBatchDelete"
            >
              <template #content>
                <p>确定要批量删除吗？</p>
              </template>
              批量删除
            </my-confirm-button>
          </el-form-item>
        </el-form>
      </template>
  
      <!--列表-->
      <el-table
        v-loading="listLoading"
        :data="roles"
        border
        highlight-current-row
        :header-cell-style="{background:'#f9f9f9'}"
        @selection-change="selsChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" width="80" label="#" />
        <el-table-column prop="name" label="服务编号" width />
        <el-table-column prop="remarks" label="说明" width />
        <el-table-column prop="createTime" label="创建时间" :formatter="formatCreatedTime" width />
        <el-table-column label="操作" width="180">
          <template #default="{ $index, row }">
            <el-button v-if="checkPermission(['admin_sysrole_update'])" type="success" icon="el-icon-edit" @click="onEdit($index, row)">编辑</el-button>
            <my-confirm-button
              v-if="checkPermission(['admin_sysrole_delete'])"
              type="delete"
              icon="el-icon-delete"
              :loading="row._loading"
              :validate-data="row"
              @click="onDelete($index, row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <my-pagination
        ref="pager"
        :total="total"
        :checked-count="sels.length"
        @get-page="getRoles"
      />
      <!--分页-->
  
      <!--新增窗口-->
      <el-dialog
        title="新增角色"
        :visible.sync="addFormVisible"
        :close-on-click-modal="false"
        width="30%"
      >
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" size="medium">
          <el-row>
            <el-col>
              <el-form-item label="角色名" prop="name">
                <el-input v-model="addForm.name" auto-complete="off" />
              </el-form-item>
            </el-col>
  
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="说明" prop="remarks">
                <el-input v-model="addForm.remarks" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <div class="dialog-footer">
            <el-button @click.native="addFormVisible = false">取消</el-button>
            <my-confirm-button type="submit" :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
          </div>
        </template>
  
      </el-dialog>
      <!--编辑-->
      <el-dialog
        title="编辑角色"
        :visible.sync="editFormVisible"
        :close-on-click-modal="false"
        width="30%"
      >
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules" size="medium">
          <el-row>
            <el-col>
              <el-form-item label="角色名" prop="name">
                <el-input v-model="editForm.name" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col>
              <el-form-item label="说明" prop="remarks">
                <el-input v-model="editForm.remarks" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <div class="dialog-footer">
            <el-button @click.native="editFormVisible = false">取消</el-button>
            <my-confirm-button type="submit" :validate="editFormValidate" :loading="editLoading" @click="onEditSubmit" />
          </div>
        </template>
  
      </el-dialog>
  
    </my-container>
  </template>
  
  <script>
  import { formatTime } from '@/utils'
  import { getRoleListPage, removeRole, editRole, addRole, batchRemoveRole, getRole } from '@/api/admin/role'
  import MyContainer from '@/components/my-container'
  import MyConfirmButton from '@/components/my-confirm-button'
  
  export default {
    name: 'Roles',
    components: { MyContainer, MyConfirmButton },
    data() {
      return {
        filter: {
          name: ''
        },
        roles: [],
        total: 0,
        sels: [], // 列表选中列
        listLoading: false,
        pageLoading: false,
        addDialogFormVisible: false,
        editFormVisible: false, // 编辑界面是否显示
        editLoading: false,
        editFormRules: {
          name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
          enabled: [{ required: true, message: '请输入状态', trigger: 'change' }]
        },
        // 编辑界面数据
        editForm: {
          id: 0,
          name: '',
          description: '',
          enabled: ''
        },
        editFormRef: null,
  
        addFormVisible: false, // 新增界面是否显示
        addLoading: false,
        addFormRules: {
          name: [{ required: true, message: '请输入角色名', trigger: 'blur' }]
        },
        // 新增界面数据
        addForm: {
          name: '',
          remarks: ''
        },
        addFormRef: null,
        deleteLoading: false
      }
    },
    mounted() {
      this.getRoles()
    },
    beforeUpdate() {
    },
    methods: {
      formatCreatedTime: function(row, column, time) {
        return formatTime(time, 'YYYY-MM-DD HH:mm')
      },
      onSearch() {
        this.$refs.pager.setPage(1)
        this.getRoles()
      },
      // 获取角色列表
      async getRoles() {
        var pager = this.$refs.pager.getPager()
        const params = {
          ...pager,
          filter: this.filter
        }
        this.listLoading = true
        const res = await getRoleListPage(params)
        this.listLoading = false
        if (!res?.success) {
          return
        }
  
        this.total = res.data.totalCount
        const data = res.data.rows
        data.forEach(d => {
          d._loading = false
        })
        this.roles = data
      },
      // 显示编辑界面
      async onEdit(index, row) {
        this.pageLoading = true
        const res = await getRole({ id: row.id })
        this.pageLoading = false
        if (res && res.success) {
          const data = res.data
          this.editForm = data
          this.editFormVisible = true
        }
      },
      closeEditForm() {
        this.$refs.editForm.resetFields()
      },
      // 显示新增界面
      onAdd() {
        this.addFormVisible = true
      },
      closeAddForm() {
        this.$refs.addForm.resetFields()
      },
      // 编辑验证
      editFormValidate: function() {
        let isValid = false
        this.$refs.editForm.validate(valid => {
          isValid = valid
        })
        return isValid
      },
      // 编辑
      async onEditSubmit() {
        this.editLoading = true
        const para = _.cloneDeep(this.editForm)
  
        const res = await editRole(para)
        this.editLoading = false
  
        if (!res?.success) {
          return
        }
  
        this.$message({
          message: this.$t('admin.updateOk'),
          type: 'success'
        })
        this.$refs['editForm'].resetFields()
        this.editFormVisible = false
        this.getRoles()
      },
      // 新增验证
      addFormValidate: function() {
        let isValid = false
        this.$refs.addForm.validate(valid => {
          isValid = valid
        })
        return isValid
      },
      // 新增
      async onAddSubmit() {
        this.addLoading = true
        const para = _.cloneDeep(this.addForm)
        const res = await addRole(para)
        this.addLoading = false
        if (!res?.success) {
          return
        }
        this.$message({
          message: this.$t('admin.addOk'),
          type: 'success'
        })
        this.$refs['addForm'].resetFields()
        this.addFormVisible = false
        this.getRoles()
      },
      // 删除
      async onDelete(index, row) {
        row._loading = true
        const para = []
        para.push(row.id)
        const res = await removeRole(para)
        row._loading = false
  
        if (!res?.success) {
          return
        }
  
        this.$message({
          message: this.$t('admin.deleteOk'),
          type: 'success'
        })
  
        this.getRoles()
      },
      // 批量删除
      async onBatchDelete() {
        const para = { ids: [] }
        para.ids = this.sels.map(s => {
          return s.id
        })
  
        this.deleteLoading = true
        const res = await batchRemoveRole(para.ids)
        this.deleteLoading = false
  
        if (!res?.success) {
          return
        }
        this.$message({
          message: this.$t('admin.batchDeleteOk'),
          type: 'success'
        })
        this.getRoles()
      },
      selsChange: function(sels) {
        this.sels = sels
      }
    }
  }
  </script>
  